package servlet.news;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdbc.DBUtils;
import model.News;
import model.NewsChannel;

@WebServlet("/NewsListServlet")
public class NewsListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection connection = DBUtils.getConn();
		try {
			PreparedStatement ps = connection.prepareStatement("select * from news");
			PreparedStatement pses = connection.prepareStatement("select * from news_channel");
			ResultSet rs = ps.executeQuery();
			ResultSet rses = pses.executeQuery();
			List<News>  newslist = new ArrayList<>();
			List<NewsChannel> newsChannellist = new ArrayList<>();
			Map<Integer,String>  map = new HashMap<>();
			while (rses.next()) {
				NewsChannel newsChannel = new NewsChannel();
				newsChannel.setId(rses.getInt("id"));
				newsChannel.setName(rses.getString("name"));
				newsChannellist.add(newsChannel);
			}
			for (NewsChannel newsChannel : newsChannellist) {
				map.put(newsChannel.getId(), newsChannel.getName());
			}
			while (rs.next()) {
				News news = new News();
				news.setId(rs.getInt("id"));
				news.setLinktype(rs.getInt("linkType"));
				news.setLinkurl(rs.getString("linkurl"));
				news.setTitle(rs.getString("title"));
				news.setContent(rs.getString("content"));
				news.setEdittime(rs.getDate("edittime"));
				news.setAddtime(rs.getDate("addtime"));
				//获得key 转换类型   
				news.setNewsChannelName((map.get(rs.getInt("channel_id"))));
				newslist.add(news);
			}			request.setAttribute("list",newslist);
			request.setAttribute("newsChannellist",newsChannellist);
			rs.close();
			rses.close();
			ps.close();
			pses.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
